Checking that variable X has type T with type annotations implies that X’s value is of
type T or a subtype of T. After such a check, it is a good practice to limit actions on X to those allowed by type T, even if a subclass of T allows
different actions. Doing otherwise will confuse your fellow developers.
Just to be clear, it is common in python to perform an action without checking first if it is possible (see "Easier to ask for forgiveness than permission."). However when type checks are
performed, they should not contradict the following actions.
This rule raises an issue when an action performed on a variable might be possible, but it contradicts a previous type check. The list of checked
actions corresponds to rules S2159, S3403, S5607, S5756, S5644,
S3862, S5797, S5795 and S5632. These other rules only detect cases where the type of a
variable is certain, i.e. it cannot be a subclass.
Noncompliant code example
def add_the_answer(param: str):
return param + 42 # Noncompliant. Fix this "+" operation; Type annotation on "param" suggest that operands have incompatible types.
# Note: In practice it is possible to create a class inheriting from both "str" and "int", but this would be a very confusing design.
Compliant solution
def add_the_answer(param: str):
return param + "42"